import { createRouter, createWebHistory } from 'vue-router';
import administratorHome from '../../components/administrator/home.vue';
import assessorHome from '../../components/assessor/homeAssessor.vue';
import employeeHome from '../../components/employee/home.vue';
import home from '../../components/first/home.vue';
import searchHome from '../../components/first/SearchHome.vue';
import login from '../../components/login/login.vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// ------------------ 路由表 ------------------
const routes = [
    { path: '/', component: home },
    { path: '/search', component: searchHome },
    { path: '/login', component: login },
    {
        path: '/login2',
        component: () =>
            import ('../../components/login/login2.vue')
    },

    {
        path: '/administrator/home',
        component: administratorHome,
        children: [{
                path: 'myself',
                component: () =>
                    import ('../../components/administrator/myself.vue'),
            },
            {
                path: 'manageEmp/addEmp',
                component: () =>
                    import ('../../components/administrator/manageEmp/addEmp.vue'),
            },
            {
                path: 'manageEmp/selectEmp',
                component: () =>
                    import ('../../components/administrator/manageEmp/selectEmp.vue'),
            },
            {
                path: 'managePlan/addPlan',
                component: () =>
                    import ('../../components/administrator/managePlan/addPlan.vue'),
            },
            {
                path: 'managePlan/selectPlan',
                component: () =>
                    import ('../../components/administrator/managePlan/selectPlan.vue'),
            },
            {
                path: 'manageDepartment/addDepartment',
                component: () =>
                    import ('../../components/administrator/manageDepartment/addDepartment.vue'),
            },
            {
                path: 'manageDepartment/selectDepartment',
                component: () =>
                    import ('../../components/administrator/manageDepartment/selectDepartment.vue'),
            },
        ],
    },
    {
        path: '/employee/home',
        component: employeeHome,
        children: [{
            path: 'myself',
            component: () =>
                import ('../../components/employee/myself.vue')
        }, {
            path: 'selectPlan',
            component: () =>
                import ('../../components/employee/selectPlan.vue')
        }]
    },
    {
        path: '/assessor/home',
        component: assessorHome,
        children: [{
            path: 'UpdataPlan',
            component: () =>
                import ('../../components/assessor/UpdataPlan.vue')
        }, {
            path: 'myself',
            component: () =>
                import ('../../components/assessor/myself.vue')
        }, {
            path: 'objection',
            component: () =>
                import ('../../components/assessor/objection.vue')
        }]
    },
    {
        path: '/login2',
        component: () =>
            import ('../../components/login/login2.vue')
    }
];

// ------------------ 创建路由 ------------------
const router = createRouter({
    history: createWebHistory(),
    routes,
});

// ------------------ 路由守卫 ------------------
router.beforeEach((to, from, next) => {
    const whiteList = ['/', '/search', '/login', '/login2'];
    const hasToken = localStorage.getItem('token');
    const empRole = localStorage.getItem('empRole');
    const isLoggingOut = window.__isLoggingOut === true;

    // 1. 白名单路径直接放行
    if (whiteList.includes(to.path)) {
        if (to.path === '/login' && hasToken && empRole) {
            // 登录页面但已登录：根据角色跳转
            if (empRole == 3) next({ path: '/administrator/home' });
            else if (empRole == 2) next({ path: '/assessor/home' });
            else if (empRole == 1) next({ path: '/employee/home' });
            else next();
        } else {
            next();
        }
    }
    // 2. 没有 token 且不是主动退出
    else if (!hasToken && !isLoggingOut && to.path !== '/login') {
        ElMessage.warning('用户未登录，请登录');
        next({ path: '/login', query: { redirect: to.fullPath } });
    }
    // 3. 其他情况正常放行
    else {
        next();
    }
});

// ------------------ axios 拦截器处理未登录 ------------------
axios.interceptors.response.use(
    (response) => {
        const code = response.data.code;
        const isLoggingOut = window.__isLoggingOut === true;
        if ([3001, 3002, 3003, 3004, 3005].includes(code) && !isLoggingOut) {
            ElMessage.warning('用户未登录，请登录');
            router.push('/login');
            return Promise.reject(new Error('未登录'));
        }
        return response;
    },
    (error) => {
        ElMessage.error(error.message);
        return Promise.reject(error);
    }
);

export default router;